/*
 * @Description: 
 * @Version: 2.0
 * @Autor: lxc
 * @Date: 2020-12-18 17:21:22
 * @LastEditors: lxc
 * @LastEditTime: 2020-12-24 14:55:22
 */
const express = require("express");
const router = express.Router();
const Classify = require("../../models/Classify");
const passport = require("passport");



// $route GET api/classify/test
// @desc 返回请求的JSON数据
// @access public
router.get("/test", (req, res) => {
    res.json({ msg: 'longin works' });
})
// $route GET api/classify/getClassifyList
// @desc 返回请求的JSON数据
// @access Private
var insertSorts = function (arr) {
    var len = arr.length;
    var preIndex, current;
    for (var i = 1; i < len; i++) {
        preIndex = i - 1;
        current = arr[i].sort;
        while (preIndex >= 0 && arr[preIndex].sort > current) {
            arr[preIndex + 1].sort = arr[preIndex].sort;
            preIndex--;
        }
        arr[preIndex + 1].sort = current;
    }
    return arr;
}
router.get("/getClassifyList", passport.authenticate('jwt', { session: false }), (req, res) => {
    Classify.find().then(classify => {
        let newClassify = insertSorts(classify);
        res.json(newClassify);
    })
})
// $route DELETE api/classify/delClassify
// @desc 删除分类
// @access Private
router.delete("/delClassify", passport.authenticate('jwt', { session: false }), (req, res) => {
    Classify.deleteOne({ _id: req.body.id }).then(classify => {
        if (classify.deletedCount) {
            res.json({ msg: '删除成功' });
        } else {
            res.json({ msg: '删除失败或分类不存在' });
        }
    }).catch(err => res.status(400).json(err))
})



// $route POST api/classify/addEidtClassify
// @desc 新增编辑分类
// @access Private
router.post("/addEidtClassify", passport.authenticate('jwt', { session: false }), (req, res) => {
    let searchObj = {
        name: req.body.name,
        sort: req.body.sort
    }
    if (req.body.id == '0') {
        Classify.findOne({ name: req.body.name }).then(classify => {
            if (classify) {
                return res.status(400).json({ msg: '已有该分类名称' })
            } else {
                const newClassify = new Classify(searchObj);
                newClassify.save().then(classify => {
                    res.json({ msg: '添加成功' });
                }, err => {
                    console.log(err);
                })
            }
        })
    } else {
        searchObj._id = req.body.id;
        Classify.findOneAndUpdate({ _id: req.body.id }, { $set: searchObj }, { new: true }).then(classify => {
            if (classify) {
                Classify.find({ name: req.body.name }).then(classify => {
                    if (classify.length > 1) {
                        return res.status(400).json({ msg: '已有该分类名称' })
                    } else {
                        res.json({ msg: '编辑成功' });
                    }
                })
            } else {
                return res.status(400).json({ msg: 'id错误' })
            }
        })
    }
})

module.exports = router;
